package com.bidevalution.controller.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bidevalution.business.context.UserRoleType;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.business.service.BeSectionProgressService;
import com.bidevalution.dao.entity.BeSectionProgress;
import com.bidevalution.support.context.SectionStateEnum;
import com.bidevalution.support.context.TencentApiConfig;
import com.chatroom.api.constant.MemberDisplay;
import com.chatroom.api.constant.MemberType;
import com.chatroom.api.dto.ChatGroupInfoDTO;
import com.chatroom.api.dto.ChatUserInfoDTO;
import com.chatroom.api.service.ChatGroupInfoApiService;
import com.chatroom.api.service.ChatGroupMemberApiService;
import com.chatroom.api.service.ChatUserInfoApiService;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.qtp.common.core.ContextHolderUtils;
import com.qtp.common.core.TSUser;
import com.qtp.core.model.Response;
import com.tls.tls_sigature.tls_sigature;
import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;

@RestController
@RequestMapping("/chatroom")
public class ChatroomController extends BaseController {
	private Logger logger = Logger.getLogger(ChatroomController.class);
	@Autowired
	private ChatGroupMemberApiService chatGroupMemberApiService;
	@Autowired
	private ChatUserInfoApiService chatUserInfoApiService;
	@Autowired
	private ChatGroupInfoApiService chatGroupInfoApiService;
	@Value("${SystemIdentify}")
	private String appKey;
	@Autowired
	private BeSectionProgressService beSectionProgressService;
	@Autowired
	private EnterPriseInfoDubboService enterPriseInfoDubboService;
	@Autowired
	private BeSectionInfoService beSectionInfoService;

	@RequestMapping(value = "/init", method = RequestMethod.POST)
	@ResponseBody
	public Response<Map<String, String>> addUser(@RequestParam("businessId") String businessId) {
		
		TSUser tsUser = getTSUser();
		List<String> roleList = getUserRole(tsUser);
		Map<String, String> dataMap = new HashMap<String, String>();
		try {
			UserRoleType userRoleType = beSectionInfoService.getUserRoleType(businessId, tsUser, roleList);
			String businessUserId = "";
			String userName = "";
			String avatar = "";
			String chatUserId = "";
			if (userRoleType != null) {
				logger.info("用户角色:"+userRoleType);
				if (userRoleType != UserRoleType.TBR) {
					if (userRoleType == UserRoleType.JGRY) {
						businessUserId = tsUser.getUserGuid();
						userName = tsUser.getUserName();
						avatar = "zxjgry.png";
					} else {
						businessUserId = tsUser.getOrgId();
						Map<String, Object> params = new HashMap<>();

						params.put("ep_guid", tsUser.getOrgId());
						// 获取请求中的参数
						Response<Map<String, Object>> response;
						try {
							response = enterPriseInfoDubboService.getEnterInfo(params);
							if (response.getResult() != null) {
								userName = String.valueOf(response.getResult().get("ep_name"));
							} else {
								userName = tsUser.getUserName();
							}
						} catch (Exception e) {
                            log.error(e.getMessage(), e);
						}
						avatar = userRoleType.getValue().toLowerCase() + ".png";
					}
					ChatUserInfoDTO chatUserInfoDTO = chatUserInfoApiService.getChatUserInfo(appKey, businessUserId);
					if(chatUserInfoDTO !=null) {
						chatUserInfoApiService.updateUser(appKey, businessUserId, userName, avatar, chatUserInfoDTO.getUserSign());
						dataMap.put("chatUserId", chatUserInfoDTO.getUserId());
						dataMap.put("appKey", appKey);
					}
					GenTLSSignatureResult result = tls_sigature.GenTLSSignatureEx(
							TencentApiConfig.tencentApiSdkAppid, appKey + "_" + businessUserId,
							TencentApiConfig.tencentApiPrivatekey);
					chatUserId = chatUserInfoApiService.addUser(appKey, businessUserId, userName, avatar,
							result.urlSig);

					HttpSession session = ContextHolderUtils.getSession();
					session.setAttribute("chatUserId", chatUserId);
					ChatGroupInfoDTO chatGroupInfoDTO = chatGroupInfoApiService.getByBusinessGroupId(appKey, businessId);
					if (chatGroupInfoDTO != null) {
						MemberType memberType = null;
						if (userRoleType == UserRoleType.JGRY) {
							memberType = MemberType.thirdManager;
						}
						if (userRoleType == UserRoleType.ZBR) {
							memberType = MemberType.firstManager;
						}
						if (userRoleType == UserRoleType.ZBDL) {
							memberType = MemberType.secondManager;
						}
						if (userRoleType == UserRoleType.JYXRY) {
							memberType = MemberType.thirdManager;
						}
						if(memberType == null) {
							return Response.fail(getTSUser().getLoginName()+"账号未初始化:"+businessUserId);
						}
//						// 查询项目阶段
//						BeSectionProgress beSectionProgress = beSectionProgressService.selectByKey(businessId,
//								SectionStateEnum.decrypting.getValue());
//						if (beSectionProgress != null) {
//							//解密阶段全部可见
							chatGroupMemberApiService.addMember(appKey, chatGroupInfoDTO.getGroupId(),
									chatUserId, memberType, MemberDisplay.Visible);
//						} else {
//							// 签到阶段，成员隐藏
//							MemberDisplay memberDisplay = MemberDisplay.Invisible;
//							if (memberType.getCode() > 0) {
//								memberDisplay = MemberDisplay.Visible;
//							}
//							chatGroupMemberApiService.addMember(appKey, beSectionChatroom.getGroupId(),
//									chatUserId, memberType, memberDisplay);
//						}

					}
				}else {
					businessUserId = tsUser.getOrgId();
					ChatUserInfoDTO chatUserInfoDTO = chatUserInfoApiService.getChatUserInfo(appKey, businessUserId);
					logger.info("chatUserInfoDTO:"+chatUserInfoDTO);
					if(chatUserInfoDTO != null) {
						chatUserId = chatUserInfoDTO.getUserId();
					}else {
						return Response.fail(businessUserId+"不存在");
					}
				}
				logger.info("chatUserId:"+chatUserId);
			}else {
				return Response.fail("当前用户没有权限访问");
			}
			dataMap.put("chatUserId", chatUserId);
			dataMap.put("appKey", appKey);
			return Response.ok(dataMap);
		} catch (Exception e) {
            log.error(e.getMessage(), e);
		}
		return Response.fail(null);
	}

}
